package com.example.weather

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        thread {
            // 读文件
            val str: String? = readFileFromRaw(R.raw.citycode)

            // 转成字符串
            val gson = Gson()
            // 获得type类
            val cityType = object : TypeToken<List<CityItem>>() {}.type // 确保这里的名字是一致的
            val cities: List<CityItem> = gson.fromJson(str, cityType) // 直接解析为 List<CityItem>

            runOnUiThread {
                // 获取ListView的引用
                val listView = findViewById<ListView>(R.id.listView)
                // 适配器
                val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, cities.map { it.city_name }) // 确保传递正确的类型
                listView.adapter = adapter
                //点击城市跳转
                listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
                    val cityCode = cities[position].city_code
                    val intent = Intent(this, MainActivity2::class.java)
                    intent.putExtra("city.code", cityCode)
                    startActivity(intent)
                }
            }

            Log.d("MainActivity", "$cities")
        }

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    fun readFileFromRaw(rawName: Int): String? {
        try {
            val inputReader = InputStreamReader(resources.openRawResource(rawName))
            val bufReader = BufferedReader(inputReader)
            var line: String? = ""
            var result: String? = ""
            while (bufReader.readLine().also({ line = it }) != null) {
                result += line
            }
            return result
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }
}